import numpy as np
import pandas as pd

# Z-Score
def z_score(df, threshold):
    mean = df.y.mean()
    std = df.y.std()
    df['z_score'] = df.y.apply(lambda x: abs(x - mean) / std)
    df['anomaly'] = df.z_score.apply(lambda x: 1 if x > threshold else 0)
    return df

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def z_score_route(data,url):
    if url:
        data1 = pd.read_excel(url)
    else:
        data1 = data

    data1.columns = ['y']
    threshold = 2
    df1 = z_score(data1.copy(), threshold)
    label1 = np.array(df1['anomaly']).reshape(-1,1)
    label = label1.tolist()
    return label

if __name__ =="__main__":
    # 读取文件
    url = 'ZScore_data.xlsx'
    data = pd.read_excel('ZScore_data.xlsx')
    label = z_score_route(data,url)

    # 输出label,label=0为正常点，label=1为异常点
    print('lable:', label)
